/**
 * Project Name:jiuselu-parent
 * File Name:CartController.java
 * Package Name:com.fxp.project.jiuselu.web.business.v1.controller.cart
 * Date:2021年11月10日 13:19
 * Copyright (c) 2021, Kai.Wang All Rights Reserved.
 */
package com.fxp.project.jiuselu.web.business.v1.controller.cart;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fxp.project.jiuselu.commons.constant.ConstantCode;
import com.fxp.project.jiuselu.commons.exceptions.JiuLuException;
import com.fxp.project.jiuselu.web.base.controller.BaseController;
import com.fxp.project.jiuselu.web.base.request.ReqBase;
import com.fxp.project.jiuselu.web.business.v1.request.cart.ReqCartAdd;
import com.fxp.project.jiuselu.web.business.v1.request.cart.ReqCartDelete;
import com.fxp.project.jiuselu.web.business.v1.request.cart.ReqCartNum;
import com.fxp.project.jiuselu.web.business.v1.request.cart.ReqCartUpdate;
import com.fxp.project.jiuselu.web.domain.CommonResult;
import com.fxp.project.jiuselu.web.models.goods.entity.JslActivity;
import com.fxp.project.jiuselu.web.models.goods.entity.JslGoodsAttr;
import com.fxp.project.jiuselu.web.models.goods.entity.JslGoodsSalePrices;
import com.fxp.project.jiuselu.web.models.goods.service.IJslGoodsAttrService;
import com.fxp.project.jiuselu.web.models.goods.vo.GoodsAttrVo;
import com.fxp.project.jiuselu.web.models.order.entity.JslCart;
import com.fxp.project.jiuselu.web.models.order.mapper.JslCartMapper;
import com.fxp.project.jiuselu.web.models.order.service.IJslCartService;
import com.fxp.project.jiuselu.web.models.order.vo.JslCartVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.jar.JarException;

/**
 * ClassName:CartController<br/>
 * Function: 购物车<br/>
 * Date:2021年11月10日 13:19<br/>
 *
 * @author Kai.Wang
 * @version 1.0.0
 * @see
 * @since JDK 8
 */
@RestController
@RequestMapping("/v1/user/cart")
public class CartController extends BaseController {

    @Autowired
    IJslCartService jslCartService;
    @Autowired
    IJslGoodsAttrService jslGoodsAttrService;
    @Autowired
    JslCartMapper jslCartMapper;

    /**
     * list: 获取当前用户的<br/>
     *
     * @param reqBase
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/11 13:24
     */
    @PostMapping("list")
    @CrossOrigin
    public CommonResult list(@RequestBody @Validated ReqBase reqBase, BindingResult result) {
        super.checkBindResult(result);
        List<JslCartVo> list = jslCartService.selectJslCartVoByUserId(super.getCurrentUserInfo().getUserId());
        for(JslCartVo lis : list){
            List<JslGoodsSalePrices> salePricesList = lis.getSalePricesList();
            Integer goodsNum = lis.getGoodsNum();
            Integer attrWeight = lis.getAttrWeight();
            Integer weight= goodsNum * attrWeight;
            for(JslGoodsSalePrices js : salePricesList){
                if(weight.compareTo(js.getMin().intValue())==1 && weight.compareTo(js.getMax().intValue())==-1){
                    js.setPrice(js.getPrice());
                }else if(weight.compareTo(js.getMax().intValue())==1){
                    js.setPrice(js.getPrice());
                }
            }
        }
        for(JslCartVo s : list){
            Long attrId = s.getAttrId();
            Long goodsId = s.getGoodsId();
            List<JslActivity> jslActivities = jslGoodsAttrService.selectGoodsActivityByGoodsId(goodsId);
            if(jslActivities.size() > 1){
                Collections.reverse(jslActivities);
            }
            s.setGoodsActivity(jslActivities);

            ListIterator<JslGoodsSalePrices> iterator = s.getSalePricesList().listIterator();
//            while (iterator.hasNext()){
//                JslGoodsSalePrices next = iterator.next();
//                if (next.getPrice()==null){
//                    iterator.remove();
//                    continue;
//                }
//
//                if (next.getPrice().compareTo(new BigDecimal("0"))==0){
//                    iterator.remove();
//                }
//            }

        }
        return CommonResult.success(list);
    }

    /**
     * list: 获取当前用户的样品购物车<br/>
     *
     * @return
     * @author Kai.Wang
     */
    @PostMapping("/sample/list")
    @CrossOrigin
    public CommonResult sampleList(Long userId) {
        List<Map<Object, String>> maps = jslCartMapper.selectSampleCartList(userId);
        return CommonResult.success(maps);
    }
    /**
     * save: 保存到购物车<br/>
     *
     * @param reqCartAdd
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/11 13:54
     */
    @PostMapping("save")
    @CrossOrigin
    public CommonResult save(@RequestBody @Validated ReqCartAdd reqCartAdd, BindingResult result) {
        super.checkBindResult(result);
        int resultNum = jslCartService.saveJslCartByUserId(reqCartAdd,super.getCurrentUserInfo().getUserId());
        if (resultNum > 0) {
            return CommonResult.success(resultNum);
        } else {
            return CommonResult.failed();
        }
    }

    /**
     * 小程序手动输入,更改商品数量
     * @param reqCartUpdate
     * @param result
     * @return
     */
    @PostMapping("/updatenum")
    @CrossOrigin
    public CommonResult updatenum(@RequestBody @Validated ReqCartUpdate reqCartUpdate, BindingResult result){
        super.checkBindResult(result);
        JslCart jslCart = jslCartService.getById(reqCartUpdate.getId());
        GoodsAttrVo goodsAttrVo = jslGoodsAttrService.selectGodosAttrVoListBtAttrId(jslCart.getAttrId());
        Integer goodsNum = reqCartUpdate.getGoodsNum();
        Integer storeCount = goodsAttrVo.getStoreCount();
        if(goodsNum > storeCount){
            throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(),"超出该商品最大库存");
        }
        if(null != jslCart && super.getCurrentUserInfo().getUserId().equals(jslCart.getUserId()) && goodsNum > 0){
            jslCart.setGoodsNum(goodsNum);
            return CommonResult.success(jslCartService.updateById(jslCart));
        }
        return CommonResult.failed("修改失败");
    }

    /**
     * num: 给购物车产品添加数量<br/>
     *
     * @param reqCartNum
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/11 13:54
     */
    @PostMapping("num/{id}")
    @CrossOrigin
    public CommonResult num(@PathVariable("id") Long id, @RequestBody @Validated ReqCartNum reqCartNum, BindingResult result) {
        super.checkBindResult(result);
        JslCart jslCart = jslCartService.getById(id);
        GoodsAttrVo goodsAttrVo = jslGoodsAttrService.selectGodosAttrVoListBtAttrId(jslCart.getAttrId());
        Integer goodsNum = jslCart.getGoodsNum() + 1;
        Integer storeCount = goodsAttrVo.getStoreCount();
        if(reqCartNum.getCartMinus()==0){
            if(goodsNum > storeCount){
                throw new JiuLuException(ConstantCode.PARAM_EXCEPTION.getCode(),"超出该商品最大库存");
            }
        }
        if (null != jslCart && super.getCurrentUserInfo().getUserId().equals(jslCart.getUserId()) && reqCartNum.getGoodsNum() > 0) {
            jslCart.setGoodsNum(reqCartNum.getGoodsNum());
            return CommonResult.success(jslCartService.updateById(jslCart));
        }
        return CommonResult.failed();
    }

    /**
     * delete: 删除当前购物车Id<br/>
     *
     * @param reqCartDelete
     * @param result
     * @return
     * @author Kai.Wang
     * @date 2021/11/11 13:54
     */
    @PostMapping("delete")
    @CrossOrigin
    public CommonResult delete(@RequestBody @Validated ReqCartDelete reqCartDelete, BindingResult result) {
        super.checkBindResult(result);
        return CommonResult.success(jslCartService.removeByIds(reqCartDelete.getIds()));
    }
}
